const path = require("path")
const webpack = require("webpack")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const fs = require('fs')
const merge = require('webpack-merge')
const CleanWebpackPlugin = require("clean-webpack-plugin")
const CopyWebpackPlugin = require('copy-webpack-plugin')
const glob = require("glob")
const autoprefixer = require('autoprefixer');
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// 动态获取入口
function getEntry(){

    let entries = glob.sync("./src/pages/**/*.js")
    let entry = {}
    let key
    entries.forEach((file) => {
        var eArr = [];
        if (/.js$/.test(file)) {
            key = file.substring(file.lastIndexOf('\/') + 1, file.lastIndexOf('.'))
            eArr.push('babel-polyfill')
            eArr.push(file)
            entry[key] = eArr
        }
    })
    // console.log('【入口文件】')
    console.log(entry)
    return entry
}

// 动态设置模板
function getHtml(){

    let templateUrl = glob.sync("./src/pages/**/*.html")
    let arr = []

    templateUrl.forEach((file) => {
        let filename = file.substring(file.lastIndexOf("\/")+1,file.lastIndexOf("."))

        let tplconf = {
            title:filename,
            template: file,
            filename: filename + ".html",
            inject:true,
            // minify:false,
            chunks:[filename].concat( ['vendor', 'commons', 'manifest'] )
        }

        arr.push(new HtmlWebpackPlugin(tplconf));
    })
    console.log(arr)
    return arr
}


module.exports =  (env,argv)=>{
    return{
        entry : getEntry(),
        resolve: {  //导入的时候不用写拓展名
            extensions: ['.js', '.vue', '.json'],
        },
        resolve: {
            alias: {
                '@': path.resolve(__dirname,'src'),
            }
        },
        output:{
            path: path.join(__dirname,'./dist/'), // 两个参数不能写反
            filename:'js/[name].[chunkhash].js'
        },
        devtool:'cheap-source-map',//只在webpack-dev-server模式有效
        module: {
            rules:[
              {
                  test: /\.js$/,
                  loader: 'babel-loader',
                  exclude: /(node_modules|bower_components)/ //不需要处理的文件夹
              },
            {
                test:/\.css$/,
                //use:['style-loader','css-loader','postcss-loader']//css不分离写法
                //css分离写法
                use:[MiniCssExtractPlugin.loader,"css-loader",{
                    loader: "postcss-loader",
                    options: {
                        plugins: [
                            autoprefixer({
                                browsers: ['ie >= 8','Firefox >= 20', 'Safari >= 5', 'Android >= 4','Ios >= 6', 'last 4 version']
                            })
                        ]
                    }
                }]
            },
            {
                test:/\.(png|jpg|gif|jpeg)$/,
                use:[
                    {
                        loader:'url-loader',
                        options:{
                            limit:5000
                        }
                    }
                ]
            }
            ]
        },
        plugins:[
            new CleanWebpackPlugin(),
           ...getHtml(),
            new MiniCssExtractPlugin({
                filename: `css/[name].css`
            }),
        ],
        optimization: {
          runtimeChunk: {
            name: 'manifest',
          },
          splitChunks: {
            minSize: 20000, // 超过20k才会被打包
            cacheGroups: {
              vendor: {
                name: "vendor",
                test: /[\\/]node_modules[\\/]/,
                chunks: "all",
                minChunks: 1
              },
              commons: {
                name: "commons",
                chunks: "all",
                minChunks: 2
              }
            }
          }
        }

    }
}
